package com.share.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.share.domain.*;

import com.share.service.SysRoleService;
import com.share.service.SysUserRoleService;
import com.share.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @program: share-admin
 * 描述：
 * @author: XLX
 * @create: 2022-11-28 10:59
 **/
@RequestMapping("sys/user")
@RestController
public class UserController extends BaseController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    BCryptPasswordEncoder passwordEncoder;



    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id){
        SysUser sysUser = sysUserService.getById(id);
        Assert.notNull(sysUser,"找不到该管理员");
        List<SysRole> roles = sysRoleService.listRolesByUserId(id);
        sysUser.setRoles(roles);
        return Result.succ(sysUser);
    }


    @GetMapping("/list")
    public Result list(String username){
        Page<SysUser> page = sysUserService.findPage(username,getPage()) ;
        return Result.succ(page);
    }


    @PostMapping("/save")
    public Result save(@RequestBody SysUser sysUser){
        sysUser.setCreated(new Date());
        sysUser.setStatu(Const.STATUS_ON);
        //默认密码
        String password = passwordEncoder.encode(Const.DEFULT_PASSWORD);
        sysUser.setPassword(password);
        sysUserService.save(sysUser);
        return Result.succ(sysUser);
    }


    @PostMapping("/update")
    public Result update(@RequestBody SysUser sysUser){
        sysUser.setUpdated(new Date());
        sysUserService.updateById(sysUser);
        return Result.succ(sysUser);
    }


    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long[] ids) {

        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));

        return Result.succ("");
    }

    @Transactional
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {

        List<SysUserRole> userRoles = new ArrayList<>();

        Arrays.stream(roleIds).forEach(r -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);

            userRoles.add(sysUserRole);
        });

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(userRoles);

        // 删除缓存
        SysUser sysUser = sysUserService.getById(userId);

        return Result.succ("");
    }

    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result repass(@RequestBody Long userId) {

        SysUser sysUser = sysUserService.getById(userId);

        sysUser.setPassword(passwordEncoder.encode(Const.DEFULT_PASSWORD));
        sysUser.setUpdated(new Date());

        sysUserService.updateById(sysUser);
        return Result.succ("");
    }






}